package com.tfswx.jcyw.dmzc.linstener;

import com.intellij.ide.AppLifecycleListener;
import com.tfswx.jcyw.dmzc.api.FwdController;
import com.tfswx.jcyw.dmzc.api.KhdController;
import com.tfswx.jcyw.dmzc.api.anno.Request;
import com.tfswx.jcyw.dmzc.dto.Api;
import com.tfswx.jcyw.dmzc.service.DlxxService;
import com.tfswx.jcyw.dmzc.service.HttpServer;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public final class MyAppLifecycleListener implements AppLifecycleListener {
    public static Integer SERVER_PORT;

    @Override
    public void appFrameCreated(@NotNull List<String> commandLineArgs) {

//        List<Class<?>> classList = Arrays.asList(FwdController.class, KhdController.class);
//
//        Map<String, Api> apiMap = new HashMap<>();
//        for (Class<?> aClass : classList) {
//            Object o = aClass.getConstructor().newInstance();
//            Request annotation = aClass.getAnnotation(Request.class);
//            String value = annotation.value();
//            Method[] methods = aClass.getDeclaredMethods();
//            for (Method method : methods) {
//                Request annotation1 = method.getAnnotation(Request.class);
//                if (annotation1 == null) {
//                    continue;
//                }
//                String value1 = annotation1.value();
//
//                String apiPath = "/" + value + "/" + value1;
//                Api api = new Api();
//                api.setM(method);
//                api.setO(o);
//                api.setMethod("post");
//                apiMap.put(apiPath, api);
//            }
//        }
//
//        // 随机数防止端口被占用，如果被占用catch后stopServer
////        int port = (int) ((Math.random() * 9 + 1) * 1000);
//        HttpServer httpServer = new HttpServer(0, apiMap, s -> {
//            try {
//                if ("/".equals(s)) {
//                    s = "/index.html";
//                }
//                URL resourceAsStream = MyAppLifecycleListener.class.getClassLoader().getResource("html" + s);
//                return IOUtils.toByteArray(resourceAsStream);
//            } catch (Exception e) {
//                return "找不到网页".getBytes(StandardCharsets.UTF_8);
//            }
//        });
//        httpServer.start();
//        SERVER_PORT = httpServer.getListeningPort();
//        log.info("服务已启动：{}", httpServer.getListeningPort());
    }

    @Override
    public void welcomeScreenDisplayed() {
        DlxxService dlxx = DlxxService.getInstance();
        if (dlxx.isDjtEnable()) {
            EventQueue.invokeLater(() -> {
            });
        }
    }
}
